package com.br.unisal.library.controller;

import java.util.HashMap;
import java.util.Map;

import javax.swing.JInternalFrame;

import com.br.unisal.library.business.LoginValidator;
import com.br.unisal.library.exception.InvalidUserLoginData;
import com.br.unisal.library.operations.settings.LoginOperationSettings;
import com.br.unisal.library.operations.settings.OperationSettingsCreator;
import com.br.unisal.library.operations.settings.OperationType;
import com.br.unisal.library.util.ParameterTypes;
import com.br.unisal.library.view.graphic.LibraryMainView;
import com.br.unisal.library.view.graphic.MainMenu;

public class LoginController {

	private String user;
	private String password;
	private LibraryMainView libraryMainView;
	private OperationSettingsCreator operationSettingsCreator;

	public LoginController(OperationType operationType, String user, String password, 
          LibraryMainView libraryMainView) {
		this.user = user;
		this.password = password;
		this.libraryMainView = libraryMainView;
	}

	public void perform() throws InvalidUserLoginData {
		LoginOperationSettings loginSettings = createLoginOperationSettings();
		LoginValidator loginValidator = new LoginValidator(loginSettings);
		createResult(loginValidator);
	}

	private void createResult(LoginValidator loginValidator) throws InvalidUserLoginData {
		boolean isRegisteredUser = loginValidator.validate();
		if(isRegisteredUser) {
			createMainLibraryFrame();
		} else {
			throw new InvalidUserLoginData();
		}
	}

	private void createMainLibraryFrame() {
		libraryMainView.disposeJInternalFrame();
              JInternalFrame jInternalFrame_MainMenu = createMainMenu();
              jInternalFrame_MainMenu.setVisible(true);
              libraryMainView.addNewJInternalFrame(jInternalFrame_MainMenu);
	}

	private LoginOperationSettings createLoginOperationSettings() {
		operationSettingsCreator = new OperationSettingsCreator();
		LoginOperationSettings operationSettings = new LoginOperationSettings(OperationType.LOGIN);
		operationSettings.setOperationSettings(createSettingsMap());
		
		return operationSettings;
	}

      	private Map<ParameterTypes, String> createSettingsMap() {
           
		Map<ParameterTypes, String> settingsMap = 
                        new HashMap<ParameterTypes, String>();
		settingsMap.put(ParameterTypes.PASSWORD, password);
		settingsMap.put(ParameterTypes.USER, user);
		return settingsMap;
	}

    private JInternalFrame createMainMenu() {
       return new MainMenu();
    }
}
